<template>
  <div class="h-6" />

  <el-menu :default-active="activeIndex2" class="el-menu-demo fixed-header" mode="horizontal" background-color="#545c64"
    text-color="#fff" active-text-color="#ffd04b" @select="handleSelect" style="height: 100px;">
    <el-menu-item index="1">logo</el-menu-item>
    <el-menu-item index="2" style="margin-left: 5%;">首页</el-menu-item>
    <el-menu-item index="3">配音制作</el-menu-item>
    <el-menu-item index="4">声音广场</el-menu-item>
    <el-menu-item index="5">百宝箱</el-menu-item>
    <el-menu-item index="6">购买会员</el-menu-item>
    <el-menu-item index="7" style="margin-left: 50%; padding-top: 20px;">
      <el-switch v-model="isDarkMode" class="mt-2" :active-icon="Moon" :inactive-icon="Sunny" size="large"
        @change="toggleTheme" />
    </el-menu-item>
    <el-dropdown class="elmenuitems" style="margin-left: 20px; padding-top: 20px;">
      <el-menu-item index="9">
        <el-avatar :src="avatarUrl" />
      </el-menu-item>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item @click="goToMemberCenter">会员中心</el-dropdown-item>
          <el-dropdown-item @click="logout">退出登录</el-dropdown-item>
          <el-dropdown-item @click="Loginregistration">登录注册</el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </el-menu>
</template>

<script lang="ts" setup>
import { ref, watch, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Moon, Sunny } from '@element-plus/icons-vue'; // 添加图标导入
import axios from 'axios';
import { ICheckUserNameResult,GetBaseURL } from '../../composables/types';
import { useToggle } from '@vueuse/shared'
import { useDark } from '@vueuse/core'

// 调用element plus 的白天黑夜主题模式
const isDark = useDark({
  storageKey: 'vitepress-theme-appearance',
})
const toggleDark = useToggle(isDark)

// 接口地址
const baseUrl: string = GetBaseURL();

// 定义事件发射器
const emit = defineEmits(['refreshParent']);

// 路由相关
const router = useRouter();
const route = useRoute();

// 组件状态
const activeIndex2 = ref('1')
const avatarUrl = ref('');
const isDarkMode = ref(false);

// 监听路由变化，更新 activeIndex2
watch(route, (to) => {
  const routeMap: { [key: string]: string } = {
    '/homepage': '2',
    '/': '3',
    '/Soundsquarepage': '4',
    '/Tinkerboxpage': '5',
    '/Purchasembpage': '6',
    '/assist': '8'
  };
  activeIndex2.value = routeMap[to.path] || '1';
}, { immediate: true });

// 处理菜单选择
const handleSelect = (key: string) => {
  const routeMap: { [key: string]: string } = {
    '2': '/homepage',
    '3': '/',
    '4': '/Soundsquarepage',
    '5': '/Tinkerboxpage',
    '6': '/Purchasembpage',
    '8': '/assist'
  };
  if (routeMap[key]) {
    router.push(routeMap[key]);
  }
}

// 设置 Cookie
function setCookie(name: string, value: string, days: number): void {
  const d = new Date();
  d.setTime(d.getTime() + (days * 24 * 60 * 60 * 1000));
  const expires = "expires=" + d.toUTCString();
  document.cookie = name + "=" + value + ";" + expires + ";path=/";
}

// 获取 Cookie
function getCookie(name: string): string | null {
  const nameEQ = name + "=";
  const ca = document.cookie.split(';');
  for (let c of ca) {
    while (c.charAt(0) === ' ') c = c.substring(1);
    if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length);
  }
  return null;
}

// 组件挂载时的初始化
onMounted(() => {
  // 初始化夜间模式
  const nightMode = getCookie('nightMode');
  isDarkMode.value = nightMode === 'dark';
  toggleTheme2(isDarkMode.value);

  // 初始化头像
  const storedAvatarUrl = getCookie('TR_vatar');
  avatarUrl.value = storedAvatarUrl || ''; // 设置默认头像 URL
})

// 切换主题并刷新父组件
function toggleTheme(value: boolean): void {
  isDarkMode.value = value;
  setCookie('nightMode', value ? 'dark' : 'light', 7);
  emit('refreshParent');

  //调用element plus的白天或黑夜模式切换
  isDark.value = !isDarkMode.value;
  toggleDark();
}

// 切换主题但不刷新父组件
function toggleTheme2(value: boolean): void {
  isDarkMode.value = value;
  setCookie('nightMode', value ? 'dark' : 'light', 7);
}

// 成功提示
const successMessage = (value: string): void => {
  ElMessage({
    message: value,
    type: 'success',
  })
}

// 错误提示
const errorMessage = (value: string): void => {
  ElMessage.error(value)
}

// 退出登录
const logout = (): void => {
  //会员退出
  memberLogout();
  //清空Cookie
  ['TR_username', 'TR_password', 'TR_vatar'].forEach(key => setCookie(key, "", 7));
  successMessage("退出登录成功");
  avatarUrl.value = "";
}

// 跳转到登录注册页面
const Loginregistration = (): void => {
  router.push('/Login');
}

// 跳转到会员中心
const goToMemberCenter = (): void => {
  router.push('/MemberCenter');
}


// 会员退出
function memberLogout(): Promise<ICheckUserNameResult> {
  return axios.post(baseUrl + '/api/user/logout', {}, {
    headers: {
      'Content-Type': 'application/json',
      'token': getCookie('TR_token'),
    },
  })
    .then(response => {
      if (response.data.code === 1) {
        return response.data as ICheckUserNameResult;
      }
      throw new Error('退出登录失败');
    });
}

</script>

<style scoped>
.h-6 {
  height: 6px;
}

.el-menu-demo {
  height: 100px;
}

.el-menu-item.is-active {
  background-color: transparent !important;
  color: #fff !important;
}

.el-menu-item:hover {
  background-color: transparent !important;
  color: #fff !important;
}
</style>